package com.ziytek.web.citizen.service;

import com.ziytek.web.citizen.constant.NumConstant;
import com.ziytek.web.citizen.model.bean.DischargeCapacity;
import com.ziytek.web.citizen.model.bean.DischargeData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.temporal.ChronoUnit;
import java.util.List;

/**
 * @author fenghx
 */
@Slf4j
@Service
public class SimpsonIntegrationService {
    /*
     *使用辛普森法则计算电流对时间的积分（容量）

     * @param currents 电流序列
     *
     * @param timeIntervalSec 采样时间间隔（秒）
     *@return 容量（Ah）
     */

    public DischargeCapacity calculateCapacity(List<DischargeData> currents) {
        DischargeCapacity capacity = new DischargeCapacity();
        if (currents.size() < NumConstant.INT_TWO) {
            capacity.setCapacity(0D);
            capacity.setTimestamp(0L);
            return capacity;
            //throw new IllegalArgumentException("电流数据至少需要2个采样点");
        }

        // 区间数
        int n = currents.size() - 1;
        double sum = currents.getFirst().getCurrent() + currents.get(n).getCurrent();

        long second = ChronoUnit.SECONDS.between(currents.getLast().getTimestamp(), currents.getFirst().getTimestamp());

        // 转换为小时单位
        double h = Math.abs(second) / 3600.0;

        // 辛普森系数计算
        for (int i = 1; i < n; i++) {
            // 奇偶项系数交替为4和2
            int coefficient = (i % 2 == 0) ? 2 : 4;
            sum += coefficient * currents.get(i).getCurrent();
        }
        // 最终容量（Ah）
        var cap = (h / 3.0) * sum;
        capacity.setCapacity(cap);
        capacity.setTimestamp(Math.abs(second));
        return capacity;
    }
}
